<script setup lang="ts">
import {ref, onMounted, onUnmounted, watch} from 'vue'
import * as echarts from 'echarts'

type EChartsOption = echarts.EChartsOption;
const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

interface Props {
  data?: string[][]
}

const props = defineProps<Props>()

watch(() => props.data, () => {
  if (chart) {
    chart.setOption({
      series: {
        data: generateFullData()
      }
    });
  }
}, {deep: true});

const generateFullData = () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setFullYear(startDate.getFullYear() - 1);

  // 创建日期到提交次数的映射
  const dataMap = new Map(props.data?.map(([date, count]) => [date, count]));

  const fullData: [string, string][] = [];
  const currentDate = new Date(startDate);

  while (currentDate <= endDate) {
    const dateStr = currentDate.toISOString().split('T')[0];
    fullData.push([dateStr, dataMap.get(dateStr) || '0']);
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return fullData;
}

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)
  const option: EChartsOption = {
    tooltip: {
      position: 'top',
      borderColor: '#fff',
      borderRadius: 10,
      confine: false,
      appendToBody: true,
      className: 'echarts-tooltip',
      formatter: (params: any) => {
        return `${params.data[0]}: ${params.data[1]} 次提交`
      }
    },
    visualMap: {
      show: false,
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'right',
      bottom: 10,
      inRange: {
        color: ['#ebedf0', '#9be9a8', '#40c463', '#30a14e', '#216e39']
      }
    },
    calendar: {
      top: 20,
      left: 30,
      right: 30,
      cellSize: [13, 13],
      range: [
        echarts.time.format(new Date().setFullYear(new Date().getFullYear() - 1), '{yyyy}-{MM}-{dd}', true),
        echarts.time.format(new Date(), '{yyyy}-{MM}-{dd}', true)
      ],
      itemStyle: {
        borderWidth: 3,
        borderColor: '#fff'
      },
      splitLine: {
        show: false,
      },
      yearLabel: {show: false},
      monthLabel: {
        nameMap: [
          '1月', '2月', '3月', '4月', '5月', '6月',
          '7月', '8月', '9月', '10月', '11月', '12月'
        ],
        position: 'end'
      },
      dayLabel: {
        show: false
      }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: generateFullData(),
      itemStyle: {
        borderRadius: 3
      }
    }
  }

  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
})
</script>

<template>
  <div class="calendar-wrapper">
    <div ref="chartRef" class="submit-calendar"></div>
  </div>
</template>

<style scoped>
.calendar-wrapper {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  margin-top: 30px;
}

.submit-calendar {
  width: 100%;
  height: 150px;
  min-width: 750px;
  position: relative;
  z-index: 1;
}

:deep(.echarts-tooltip) {
  z-index: 9999 !important;
}

@media screen and (max-width: 768px) {
  .submit-calendar {
    width: 750px;
    min-width: 750px;
  }
}
</style>
